QNW_TS_ServerCore = QNW_TS_ServerCore or {}

local this = QNW_TS_ServerCore
this.taskMap = {}
this.taskCategoryMap = {}

--注册任务类型
function QNW_TS_ServerCore.registerTaskCategory(_taskCategory)
    this.taskCategoryMap[_taskCategory.Type] = _taskCategory
    if QNW_TS_Util.isServer() then
        _taskCategory.registerServer()
    end
    QNW_TS_ServerCommand.registerTaskCategory(_taskCategory)
end

--注销任务类型
function QNW_TS_ServerCore.unregisterTaskCategory(_taskCategory)
    this.taskCategoryMap[_taskCategory.Type] = nil
    this.taskMap[_taskCategory.Type] = nil
    if QNW_TS_Util.isServer() then
        _taskCategory.unregisterServer()
    end
    QNW_TS_ServerCommand.unregisterTaskCategory(_taskCategory)
end

--注册任务
function QNW_TS_ServerCore.registerTask(_task)
    local pool = this.taskMap[_task.taskCategory.Type]
    if not pool then
        pool = QNW_TS_WeightPool:new()
        this.taskMap[_task.taskCategory.Type] = pool
    end
    pool:add(_task, _task.weight)
end

--注销任务
function QNW_TS_ServerCore.unregisterTask(_task)
    local pool = this.taskMap[_task:getTaskCategory().Type]
    if pool then
        pool:remove(_task.Type)
    end
end

function QNW_TS_ServerCore.online(_player, _time)
    for k, v in pairs(this.taskCategoryMap) do
        QNW_TS_ServerCommand.registerTaskCategory(v)
        local pool = this.taskMap[v.Type]
        v.online(pool, _player, _time)
    end
end

--生成任务
--_taskCategory 任务类型
--_isDifferent 是否为每个玩家生成不同任务
function QNW_TS_ServerCore.generateTask(_taskCategory, _isDifferent, _param1, _param2, _param3, _param4, _param5)
    local playerList = getOnlinePlayers()
    if not playerList then
        playerList = ArrayList.new()
        playerList:add(getPlayer())
    end
    local pool = this.taskMap[_taskCategory.Type]
    if _isDifferent then
        for i = 0, playerList:size() - 1 do
            local player = playerList:get(i)
            local taskList = _taskCategory.generateTask(pool, _param1, _param2, _param3, _param4, _param5)
            for k, v in pairs(taskList) do
                QNW_TS_ServerCommand.releaseTask(v, player)
            end
        end
    else
        local taskList = _taskCategory.generateTask(pool, _param1, _param2, _param3, _param4, _param5)
        for k, v in pairs(taskList) do
            QNW_TS_ServerCommand.releaseTask(v)
        end
    end
end

